//
//  AFNetworkTool.m
//  Struggle
//
//  Created by Zyf on 16/7/6.
//  Copyright © 2016年 lexiao. All rights reserved.
//

#import "AFNetworkTool.h"

@implementation AFNetworkTool

+ (void)JSONDataWithUrl:(NSString *)url withDic:(NSMutableDictionary *)dic success:(void (^)(id))success fail:(void (^)())fail {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"image/png", nil];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSArray * kArrayKeys = [dic allKeys];
    
    NSArray *resultArray = [kArrayKeys sortedArrayUsingSelector:@selector(compare:)];
    //准备拼接token数据
    NSString * tokenStr = @"";
    for (NSString * newkey in resultArray) {
        tokenStr = [tokenStr stringByAppendingFormat:@"%@=%@,",newkey,[dic objectForKey:newkey]];
    }
    
    
    //拼接token数据结束
    tokenStr = [tokenStr substringToIndex:([tokenStr length]-1)];
    
//    NSString *kk = [tokenStr substringFromIndex:tokenStr.length - 1];
    // url编码
//    tokenStr =[AFNetworkTool encodeToPercentEscapeString:tokenStr];
    //md5加密
    NSLog(@"_token: %@", tokenStr);
    
    NSString * newtokenStr = [AFNetworkTool md5:tokenStr];
    //转换成小写
    newtokenStr = newtokenStr.lowercaseString;
    //存入字典
    NSLog(@"MD5Token: %@", newtokenStr);
    [dic setValue:newtokenStr forKey:@"_token"];
    
    NSLog(@"%@", dic);
    
    [manager POST:url parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if (success) {
            success(JSON);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (fail) {
            
            fail(error);
            NSLog(@"%@",error);
        }
    }];
}

+ (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, strlen(cStr), result );
    return [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

@end
